import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'


import ElementUI from 'element-ui' //手动变红
import '../node_modules/element-ui/lib/theme-chalk/index.css' //手动变红
// import 'element-ui/lib/theme-chalk/index.css'

//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes/index'
import Mock from './mock'
// Mock.bootstrap();
import './styles/comm.css'
import './common/js/cofig'
import 'font-awesome/scss/font-awesome.scss'
import axios from 'axios';
import '@/utils/global' //全局路由
import Home from './views/Home.vue'

function _import(s) {
  return resolve => require(['./views' + s], resolve)
};
Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)

//NProgress.configure({ showSpinner: false });

import {
  query
} from './api/api';
const router = new VueRouter({
  routes
})
let getRouter;
router.beforeEach((to, from, next) => {
  console.log('beforeEach');



  if (to.path == '/login') {
    sessionStorage.removeItem('user');
  }
  console.log(JSON.stringify(to))
  if (to.path == '/account/register' || to.path == '/account/ft_password') {
    next();
    return false;
  }
  let key = JSON.parse(sessionStorage.getItem('key'));

  console.log(key)
  if (!key && to.path != '/login') {
    next({
      path: '/login',
    })
  } else {
    let Params = {
      token: key,
      pageNo: 1,
      pageSize: 20
    };
    console.log('Params.token=' + Params.token)
    if (key) {

      console.log('token:' + key)
      axios.interceptors.request.use(
        config => {
          if (key) { // 判断是否存在token，如果存在的话，则每个http header都加上token
            key = JSON.parse(sessionStorage.getItem('key'))
            console.log('usekey=' + key)
            config.headers.token = key;
            console.log(1)
          }
          return config;
        },
        err => {
          return Promise.reject(err);
        });

    }
    if (!getRouter) { //不加这个判断，路由会陷入死循环
      if (getObjArr('menu')) {
        getRouter = getObjArr('menu');
        console.log(getRouter)
        getRouter = filterAsyncRouter(getRouter);
        router.addRoutes(getRouter);

        console.log(router)
        // next({
        //   path: 'users',
        // })

        console.log(getRouter)
        for (var i in getRouter) {
          router.options.routes.push(getRouter[i])
        }

      } else { //从localStorage拿到了路由

        let key = JSON.parse(sessionStorage.getItem("key"));
        let params = {
          token: key
        };
        query(params).then(r => {
          if (r.code !== 0) {
            this.$message({
              message: r.message,
              type: "error"
            });
          } else {
            getRouter = r.data.list;
            getRouter = filterAsyncRouter(getRouter);
            router.addRoutes(getRouter);
            for (var i in getRouter) {
              router.options.routes.push(getRouter[i])
            }

            global.antRouter = router;
            alert('12=' + global.antRouter.options.routes.length)

            console.log(router)
            // next({
            //   path: 'users',
            // })

            console.log(global.antRouter)
            return false;
            // console.log(router)

            // router
          }
        });
      }
    }
    if (to.matched.length === 0) {
      //如果未匹配到路由
      next('/404')
      //如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
    } else {
      next(); //如果匹配到正确跳转
    }

  }
})

//router.afterEach(transition => {
//NProgress.done();
//});

function routerGo(to, next) {
  getRouter = filterAsyncRouter(getRouter) //过滤路由
  router.addRoutes(getRouter) //动态添加路由
  global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
  next({ ...to,
    replace: true
  })
}

function saveObjArr(name, data) { //localStorage 存储数组对象的方法
  localStorage.setItem(name, JSON.stringify(data))
}

function getObjArr(name) { //localStorage 获取数组对象的方法
  return JSON.parse(window.localStorage.getItem(name));

}

function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.path) {
      // if (route.component === 'Layout') { //Layout组件特殊处理
      //   route.component = Layout
      // } else {
      if (route.path == '/') {
        route.component = _import('/home');
      } else {

        route.component = _import(route.path)
      }
      // }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}


new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')